package cn.wolfcode.trip.admin.filter;


import cn.wolfcode.trip.base.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * 图片过滤器
 */
public class ImageFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //从当前的请求对象中获取请求的资源路径
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        //拼接成完整的路径,判断是否存在该资源
        File file=new File(UploadUtil.PATH+uri);
        //是否存在
        if(file.exists()){
            servletResponse.getOutputStream().write(FileUtils.readFileToByteArray(file));
        }else {
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
